import { Module } from 'vuex'
import { userLogin, userLogout, getOrgInfo, getOrganTree } from '@/api/user'
import { removeToken, setToken } from '@/utils/auth'
import { managerOrganIds, enterpriseId } from '@/config/config'

export interface UserState {
  userName: string;
  userInfo: {
    userName?: string;
    userId?: string;
    name?: string;
    email?: string;
    avatar?: string;
    owner?: {
      id: string;
      name: string;
      type: string
    },
    enterpriseId?: string;
    organId?: string;
    organName?: string;
  },
  userRole: string[];
  userGroup: string[];
  isManager: boolean;

  // 所有组织机构树
  allOrganTree: any[],
  // 用户权限范围内的组织机构树（TOC展示所有组织架构）
  organTree: any[];
  // 用户所拥有的组织机构权限ID（TOC为空查询所有，其他组织机构包含当前部门和子部门）
  authOrganIds?: string[];
}

// eslint-disable-next-line
const user: Module<UserState, any> = {
  namespaced: true,
  state: () => ({
    userName: '',
    userInfo: {},
    userRole: [],
    userGroup: [],
    allOrganTree: [],
    organTree: [],
    authOrganIds: [],
    isManager: true,
  }),
  getters: {
    getUserName (state) {
      return state.userName
    },
    getUserInfo (state) {
      return state.userInfo
    },
    getUserRoles (state) {
      return state.userRole
    },
    getUserGroups (state) {
      return state.userGroup
    },
    getOrganTree (state) {
      return state.organTree
    },
    getAllOrganTree (state) {
      return state.allOrganTree
    },
    getAuthOrganIds (state) {
      return state.authOrganIds
    },
    getIsManager (state) {
      return state.isManager
    }
  },
  mutations: {
    SET_USER_NAME (state, payload) {
      state.userName = payload
    },
    SET_USER_INFO (state, payload) {
      state.userInfo = payload
    },
    SET_USER_ROLES (state, payload) {
      state.userRole = payload
    },
    SET_USER_GROUPS (state, payload) {
      state.userGroup = payload
    },
    SET_ALL_ORGAN_TREE (state, payload) {
      state.allOrganTree = payload
    },
    SET_ORGAN_TREE (state, payload) {
      state.organTree = payload
    },
    SET_AUTH_ORGANIDS (state, payload) {
      state.authOrganIds = payload
    },
    SET_IS_MANAGER (state, payload) {
      state.isManager = payload
    },
  },
  actions: {
    setUserInfo ({ commit }, data) {
      commit('SET_USER_INFO', data)
      commit('SET_USER_NAME', data.name)
    },
    setUserRoles ({ commit }, data) {
      commit('SET_USER_ROLES', data)
    },
    setUserGroups ({ commit }, data) {
      commit('SET_USER_GROUPS', data)
    },
    setOrganTree ({ commit }, data) {
      commit('SET_ORGAN_TREE', data)
    },
    // login ({ commit }, data) {
    //   return new Promise((resolve, reject) => {
    //     userLogin(data).then(res => {
    //       if (res.data) {
    //         const { userName, userId, name, email, avatar, userRole, owner, properties, token, userGroup } = res.data.record
    //         const enterpriseId = properties ? properties.enterpriseId : ''
    //         commit('SET_USER_INFO', { userName, userId, name, email, avatar, owner, enterpriseId })
    //         commit('SET_USER_NAME', name || userName)
    //         commit('SET_USER_ROLES', userRole || [])
    //         commit('SET_USER_GROUPS', userGroup || [])
    //         let organId = managerOrganIds[0]
    //         let organName = "TOC"
    //         let isToc = false
    //         if (userGroup.length > 0) {
    //           userGroup.forEach((ele:any) => {
    //             getOrgInfo(ele).then(r => {
    //               if (r.data && managerOrganIds.includes(r.data.organId)) {
    //                 isToc = true
    //               }else{
    //                 organId = r.data.organId
    //                 organName = r.data.name
    //               }
    //             })
    //           })
    //           setToken(token)
    //           resolve(res)
    //         } else {
    //           setToken(token)
    //           resolve(res)
    //         }
    //         if (isToc) {
    //           organId = managerOrganIds[0]
    //           organName = "TOC"
    //         }
    //         commit('SET_USER_INFO', { userName, userId, name, email, avatar, owner, enterpriseId, organId, organName })
    //       } else {
    //         reject(res)
    //       }
    //     }).catch(reject)
    //   })
    // },
    setUserStore ({ commit }, data) {
      const { userName, userId, name, email, avatar, userRole, owner, properties, token, userGroup } = data.record
      const enterpriseId = properties ? properties.enterpriseId : ''
      const organId = userGroup.indexOf(managerOrganIds[0])>-1?managerOrganIds[0]:userGroup[0]
      commit('SET_USER_INFO', { userName, userId, name, email, avatar, owner, enterpriseId, organId })
      commit('SET_USER_ROLES', userRole || [])
      commit('SET_USER_GROUPS', userGroup || [])
      setToken(token)
    },
    login ({ dispatch }, data) {
      return new Promise((resolve, reject) => {
        localStorage.clear()
        sessionStorage.clear()
        userLogin(data).then(res => {
          if (res.data) {
            dispatch('setUserStore', res.data).then(() => {
              resolve(res.data)
            })
          } else {
            reject(res)
          }
        }).catch(reject)
      })
    },
    getOrgan ({ commit, rootState }) {
      return new Promise((resolve, reject) => {
        const organId = rootState.user?.userInfo?.organId
        const params = {
          enterpriseIds: [rootState.user?.userInfo?.enterpriseId],
          state: 'VALID',
          id: ''
        }
        // 若登录用户为TOC，查询所有组织机构
        /* if(managerOrganIds.includes(organId)){
          params.id = "";
        }else{
          params.id = organId;
        } */
        getOrganTree(params).then(res => {
          const data = res.data
          console.log(data);
          formatterOrganTree(data)
          if (data) {
            commit('SET_ALL_ORGAN_TREE', data)
            if (managerOrganIds.includes(organId)) {
              commit('SET_ORGAN_TREE', data)
              commit('SET_AUTH_ORGANIDS', [])
              commit('SET_IS_MANAGER',true)
            } else {
              commit('SET_IS_MANAGER',false)
              getUserOrganTree(commit, data, organId)
            }
            resolve(res)
          } else {
            reject(res)
          }
        }).catch(reject)
      })
    },
    logout ({ commit }, data) {
      return new Promise((resolve, reject) => {
        userLogout(data).then(res => {
          commit('SET_USER_INFO', {})
          commit('SET_USER_NAME', '')
          commit('SET_USER_ROLES', [])
          commit('SET_USER_GROUPS', [])
          commit('SET_ALL_ORGAN_TREE', [])
          commit('SET_ORGAN_TREE', [])
          commit('SET_AUTH_ORGANIDS', [])
          removeToken()
          resolve(res)
        }).catch(reject)
      })
    }
  }
}

// 递归获取用户组织架构
const getUserOrganTree = (commit:any, data: any, id: string) => {
  let list : any = []
  data.forEach((element:any) => {
    if (element.data.organId === id) {
      list = [element]
    }
  })
  if (list.length > 0) {
    commit('SET_ORGAN_TREE', list)
    const authIds: string[] = []
    getOrganIds(authIds, commit, list)
    commit('SET_AUTH_ORGANIDS', authIds)
  } else {
    data.forEach((element:any) => {
      getUserOrganTree(commit, element.children, id)
    })
  }
}

const formatterOrganTree = (arr: any) => {
  arr.forEach((item: any) => {
    item.organizationId = item.data.organId
    item.organizationName = item.data.name
    if (item.children) {
      formatterOrganTree(item.children)
    }
  })
}

const getOrganIds = (authIds:string [], commit:any, list: any) => {
  list.forEach((element:any) => {
    authIds.push(element.data.organId)
    if (element.children.length > 0) {
      getOrganIds(authIds, commit, element.children)
    }
  })
}

export default user

// import { Module } from 'vuex'
// import { userLogin, userLogout } from '@/api/user'
// import { removeToken, setToken } from '@/utils/auth'

// export interface UserState {
//   userName: string;
//   userInfo: {
//     userName?: string;
//     userId?: string;
//     name?: string;
//     email?: string;
//     avatar?: string;
//     owner?: {
//       id: string;
//       name: string;
//       type: string
//     },
//     enterpriseId?: string;
//   },
//   roles: string[],
//   userGroup: string[],
//   organTree: any[]

// }

// // eslint-disable-next-line
// const user: Module<UserState, any> = {
//   namespaced: true,
//   state: () => ({
//     userName: '',
//     userInfo: {},
//     roles: [],
//     userGroup:[],
//     organTree: []
//   }),
//   getters: {
//     getUserName (state) {
//       return state.userName
//     },
//     getUserInfo (state) {
//       return state.userInfo
//     },
//     getUserRoles (state) {
//       return state.roles
//     },
//         getOrganTree (state) {
//       return state.organTree
//     },
//   },
//   mutations: {
//     SET_USER_NAME (state, payload) {
//       state.userName = payload
//     },
//     SET_USER_INFO (state, payload) {
//       state.userInfo = payload
//     },
//     SET_USER_ROLES (state, payload) {
//       state.roles = payload
//     },
//     SET_USER_GROUPS (state, payload) {
//       state.userGroup = payload
//     },
//   },
//   actions: {
//     setUserInfo ({ commit }, data) {
//       commit('SET_USER_INFO', data)
//       commit('SET_USER_NAME', data.name)
//     },
//     setUserRoles ({ commit }, data) {
//       commit('SET_USER_ROLES', data)
//     },
//     login ({ dispatch }, data) {
//       return new Promise((resolve, reject) => {
//         userLogin(data).then(res => {
//           if (res.data) {
//             dispatch('setUserStore', res.data).then(() => {
//               resolve(res.data)
//             })

//           } else {
//             reject(res)
//           }
//         }).catch(reject)
//       })
//     },
//     getOrgan ({ commit, rootState }) {
//       return new Promise((resolve, reject) => {
//         const organId = rootState.user?.userInfo?.organId
//         const params = {
//           enterpriseIds: [rootState.user?.userInfo?.enterpriseId],
//           state: 'VALID',
//           id: ''
//         }
//         // 若登录用户为TOC，查询所有组织机构
//         /* if(managerOrganIds.includes(organId)){
//           params.id = "";
//         }else{
//           params.id = organId;
//         } */
//         getOrganTree(params).then(res => {
//           const data = res.data
//           console.log(data);
//           formatterOrganTree(data)
//           if (data) {
//             commit('SET_ALL_ORGAN_TREE', data)
//             if (managerOrganIds.includes(organId)) {
//               commit('SET_ORGAN_TREE', data)
//               commit('SET_AUTH_ORGANIDS', [])
//               commit('SET_IS_MANAGER',true)
//             } else {
//               commit('SET_IS_MANAGER',false)
//               getUserOrganTree(commit, data, organId)
//             }
//             resolve(res)
//           } else {
//             reject(res)
//           }
//         }).catch(reject)
//       })
//     },
//     logout ({ commit }, data) {
//       return new Promise((resolve, reject) => {
//         userLogout(data).then(res => {
//           commit('SET_USER_INFO', {})
//           commit('SET_USER_NAME', '')
//           commit('SET_USER_ROLES', [])
//           removeToken()
//           resolve(res)
//         }).catch(reject)
//       })
//     },
//     const formatterOrganTree = (arr: any) => {
//   arr.forEach((item: any) => {
//     item.organizationId = item.data.organId
//     item.organizationName = item.data.name
//     if (item.children) {
//       formatterOrganTree(item.children)
//     }
//   })
// },
//     setUserStore ({ commit }, data) {
//       const { userName, userId, name, email, avatar, userRole, owner, properties, token, userGroup } = data.record
//       const enterpriseId = properties ? properties.enterpriseId : ''
//       commit('SET_USER_INFO', { userName, userId, name, email, avatar, owner, enterpriseId })
//       commit('SET_USER_ROLES', userRole || [])
//       commit('SET_USER_GROUPS', userGroup || [])
//       setToken(token)
//     },

//   }
// }

// export default user

